<template>
  <n-modal
    :title="`重置 ${user?.username} 的用户密码`"
    v-model:show="show"
    preset="dialog"
    :show-icon="false"
    size="huge"
  >
    <n-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-placement="left"
      mt-30
    >
      <n-form-item label="密码" path="password">
        <n-input
          type="password"
          placeholder="请输入用户密码"
          show-password-on="mousedown"
          v-model:value="formData.password"
        />
      </n-form-item>
    </n-form>
    <template #action>
      <n-button type="primary" :loading="loading" @click="handleSubmit">
        提交
      </n-button>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { sysUserApi } from "@/api";
import type { FormInst, FormRules } from "naive-ui";
import { requiredRule, REGEXP_PWD } from "@/utils";

const props = defineProps<{ user?: User }>();

const show = ref(false);
const loading = ref(false);
const formRef = ref<FormInst>();
const formData = ref({
  password: "",
});
const formRules: FormRules = {
  password: [
    requiredRule("请输入用户密码"),
    {
      pattern: REGEXP_PWD,
      message: "密码为6-18位数字/字符/符号，至少2种组合",
      trigger: "input",
    },
  ],
};

const handleSubmit = async () => {
  if (!props.user?.id) return;
  await formRef.value?.validate();
  loading.value = true;
  try {
    const { status } = await sysUserApi.repass({
      id: props.user.id,
      password: formData.value.password,
    });
    if (!status) return;
    window.$message.success("重置密码成功");
    show.value = false;
  } finally {
    loading.value = false;
  }
};

const funShow = () => (show.value = true);
defineExpose({ show: funShow });
</script>
